package com.health.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.db.FDbManager;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.AbstractRequest;
import com.litesuits.http.request.FileRequest;
import com.litesuits.http.response.Response;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * 下载工具
 * 
 * @author zzx
 *
 */
public class DownLoadTools {

	protected static final String TAG = "download";
	private Context context;
	private NotificationManager manager;

	private Notification notification;
	private long progress;
	private RemoteViews contentView;

	private String downFileUrl;// 下载url
	private String downFilePath;// 下载到所在位置

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {// 更改进度条的进度

		public void handleMessage(Message msg) {

			contentView.setProgressBar(R.id.pb, 100, (int) progress, false);

			notification.contentView = contentView;

			manager.notify(0, notification);

			super.handleMessage(msg);

		};

	};

	public DownLoadTools(Context context) {
		this.context = context;
	}

	// private AjaxCallBack<File> getCallBack() {
	// return new AjaxCallBack<File>() {
	//
	// @Override
	// public void onFailure(Throwable t, int errorNo, String strMsg) {// 下载失败
	// super.onFailure(t, errorNo, strMsg);
	// Log.i(TAG, "下载失败..." + t.getStackTrace() + strMsg);
	// Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
	// manager.cancel(0);
	// }
	//
	// @Override
	// public void onStart() {// 开始下载
	// super.onStart();
	// Log.i(TAG, "开始下载...");
	// sendNotification();
	// }
	//
	// @Override
	// public void onSuccess(File t) {// 下载成功
	// super.onSuccess(t);
	// Log.i(TAG, "下载完成...");
	// manager.cancel(0);
	// Toast.makeText(context, "数据同步成功", Toast.LENGTH_SHORT).show();
	//
	// }
	//
	// @Override
	// public void onLoading(long count, long current) {// 正在下载
	// super.onLoading(count, current);
	// Log.i(TAG, "progress = " + progress);
	// if (current != count && current != 0) {
	// progress = (int) (current / (float) count * 100);
	// } else {
	// progress = 100;
	// }
	// handler.sendEmptyMessage(0);
	// }
	//
	// };
	//
	// }

	// @SuppressWarnings("deprecation")
	// public void download(String url, String filePath) {
	// if (!copyDB()) {
	// Toast.makeText(context, "复制文件失败", Toast.LENGTH_SHORT).show();
	// return;
	// }
	// FinalHttp http = new FinalHttp();
	// if (!isExternalStorageAvaliable()) {
	// return;
	// }
	// File f = new File(filePath);
	// if (f.exists()) {
	// f.delete();
	// }
	//
	// manager = (NotificationManager)
	// context.getSystemService(Context.NOTIFICATION_SERVICE);
	// notification = new Notification(R.drawable.ic_launcher, "数据同步中...",
	// System.currentTimeMillis());
	// http.download(url, filePath, getCallBack());
	//
	// }

	/**
	 * @param url
	 *            下载地址
	 * @param filePath
	 *            存放地址
	 */
	public void downloadFile(String url, String filePath) {
		this.downFilePath = filePath;
		this.downFileUrl = url;
		if (!copyDB()) {
			Toast.makeText(context, "复制文件失败", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!isExternalStorageAvaliable()) {
			return;
		}
		FDbManager.dropDB();
		// 删除数据库
		File f = new File(filePath);
		if (f.exists()) {
			f.delete();
		}
		// 删除KioskDB.db-journal文件
		String dbPath_journal = Environment.getExternalStorageDirectory().getAbsolutePath() + GlobalConts.TYPE_DBFILENAME
				+ "/EhrApp.db-journal";
		File f_journal = new File(dbPath_journal);
		if (f_journal.exists()) {
			f_journal.delete();
		}
		// 删除bd_dd.db-journal文件
		// String df2 =
		// Environment.getExternalStorageDirectory().getAbsolutePath()+GlobalConts.TYPE_DBFILENAME+
		// "/bd_dd.db";
		// File dff2 = new File(df2);
		// if (dff2.exists()) {
		// dff2.delete();
		// }
		String df1 = Environment.getExternalStorageDirectory().getAbsolutePath() + GlobalConts.TYPE_DBFILENAME + "/bd_dd.db-journal";
		File dff1 = new File(df1);
		if (dff1.exists()) {
			dff1.delete();
		}
		if (GlobalConts.isNetworkAvailable(context)) {
			try {
				// DownLoadTask task = new DownLoadTask(context, url, filePath);
				// task.execute();
				download(url, filePath);
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(context, "数据同步失败", Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(context, "请检查网络连接", Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 判断SD卡是否可用
	 * 
	 * @return
	 */
	public boolean isExternalStorageAvaliable() {

		String state = Environment.getExternalStorageState();

		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			Toast.makeText(context, "未检测到SD卡...", Toast.LENGTH_SHORT).show();
			return false;
		}

	}

	/**
	 * 发送通知
	 */
	public void sendNotification() {
		contentView = new RemoteViews(context.getPackageName(), R.layout.notify_view);
		contentView.setProgressBar(R.id.pb, 100, 0, false);
		notification.contentView = contentView;
		manager.notify(0, notification);
	}

	/**
	 * 当界面停止的时候取消下载
	 */

	/**
	 * 备份数据库
	 * 
	 * @return
	 * @author 王婷婷
	 * @date 2017年2月21日 下午2:24:03
	 */
	private boolean copyDB() {

		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File path = Environment.getExternalStorageDirectory();
			String lujing = path.getPath() + "/nova/download/";
			Calendar c = Calendar.getInstance();
			String date = c.get(Calendar.YEAR) + "" + (c.get(Calendar.MONTH) + 1) + "" + c.get(Calendar.DAY_OF_MONTH)
					+ "" + c.get(Calendar.HOUR_OF_DAY) + "" + c.get(Calendar.MINUTE) + "" + c.get(Calendar.SECOND) + "";

			File dir = new File(lujing);
			if (!dir.exists()) {
				dir.mkdirs();
			}
//			SharedPreferences sp = context.getSharedPreferences(GlobalConts.SHAREPREFRENCE_NAME, Activity.MODE_PRIVATE);
			
			String org_village_id = "v3_" +SPUtil.getStr_jdrno(context);// sp.getString("str_jdrno", "0");
			String addr = BluetoothAdapter.getDefaultAdapter().getAddress();
			addr = addr.replace(":", "");
			String textname = org_village_id + "_" + addr + "_" + date + "_PAD" + "_ehrapp.db";
			OutputStream os = null;
			InputStream is = null;
			try {
				is = new FileInputStream(new File(NovaApplication.dbPath));
				os = new FileOutputStream(new File(lujing + textname));
				byte[] buffer = new byte[1024];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					os.write(buffer, 0, count);
				}

				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
				try {
					is.close();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
		return false;
	}

	// private ProgressDialog downProgress;
	private LiteHttp liteHttp;
	// private String url;
	// private String filePath;

	private void download(String url, String filePath) {
		// downProgress = new ProgressDialog(context);
		// downProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// downProgress.setIndeterminate(false);
		// downProgress.show();

		initLiteHttp();
		liteHttp.executeAsync(new FileRequest(url, filePath).setHttpListener(new HttpListener<File>() {
			@Override
			public void onStart(AbstractRequest<File> request) {
				super.onStart(request);
				showWaitDialog();
				// System.out.println("liteHttp------onStart");
			}

			@Override
			public void onCancel(File data, Response<File> response) {
				super.onCancel(data, response);
				// System.out.println("liteHttp------onCancel");

				stopWaitDialog();
			}

			@Override
			public void onEnd(Response<File> response) {
				super.onEnd(response);
				// System.out.println("liteHttp------onEnd");
				stopWaitDialog();
			}

			@Override
			public void onFailure(HttpException e, Response<File> response) {
				super.onFailure(e, response);
				stopWaitDialog();
				// System.out.println("liteHttp------onFailure");
				// Toast.makeText(context, "同步失败，请重试...",
				// Toast.LENGTH_LONG).show();
				showDownloadFailure();

			}

			@Override
			public void onLoading(AbstractRequest<File> request, long total, long len) {
				super.onLoading(request, total, len);
				// System.out.println("onLoading");
			}

			@Override
			public void onRedirect(AbstractRequest<File> request, int max, int times) {
				super.onRedirect(request, max, times);
				// System.out.println("liteHttp------onRedirect");
			}

			@Override
			public void onRetry(AbstractRequest<File> request, int max, int times) {
				super.onRetry(request, max, times);
				// System.out.println("liteHttp------onRetry");
			}

			@Override
			public void onSuccess(File data, Response<File> response) {
				super.onSuccess(data, response);
				stopWaitDialog();
				FDbManager.init(context);
				// System.out.println("liteHttp------onSuccess");
				// Toast.makeText(context, "下载成功",
				// Toast.LENGTH_LONG).show();
				// FDbManager.init(context);
				Toast.makeText(context, "数据同步成功,正在重启...", Toast.LENGTH_LONG).show();
				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						/**
						 * 要执行的操作
						 */
						RestartAPPTool.restartAPP(context);
					}
				}, 2000);// 3秒后执行Runnable中的run方法
			}

			@Override
			public void onUploading(AbstractRequest<File> request, long total, long len) {
				super.onUploading(request, total, len);
				// System.out.println("liteHttp------onUploading");
			}

		}));
	}

	/**
	 * 单例 keep an singleton instance of litehttp
	 */
	private void initLiteHttp() {
		if (liteHttp == null) {
			HttpConfig config = new HttpConfig(context) // configuration
														// quickly
					.setDebugged(true) // log output when debugged
					.setDetectNetwork(true) // detect network before connect
					.setDoStatistics(true) // statistics of time and traffic
					.setUserAgent("Mozilla/5.0 (...)") // set custom
														// User-Agent
					.setTimeOut(200000, 200000); // connect and socket
												// timeout: 10s
			liteHttp = LiteHttp.newApacheHttpClient(config);
		} else {
			liteHttp.getConfig() // configuration directly
					.setDebugged(true) // log output when debugged
					.setDetectNetwork(true) // detect network before connect
					.setDoStatistics(true) // statistics of time and traffic
					.setUserAgent("Mozilla/5.0 (...)") // set custom
														// User-Agent
					.setTimeOut(200000, 200000); // connect and socket
												// timeout: 10s
		}
	}
	//
	// class DownLoadTask extends AsyncTask<Void, Integer, Void> {
	//
	// public DownLoadTask(Context context, String url, String filePath) {
	// super();
	// // this.context = context;
	// // this.url = url;
	// // this.filePath = filePath;
	// downProgress = new ProgressDialog(context);
	// downProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	// downProgress.setIndeterminate(false);
	// downProgress.show();
	// initLiteHttp();
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	// super.onPostExecute(result);
	// downProgress.dismiss();
	//
	// // Toast.makeText(context, "数据同步成功,正在重启...",
	// // Toast.LENGTH_LONG).show();
	// // Handler handler = new Handler();
	// // handler.postDelayed(new Runnable() {
	// // @Override
	// // public void run() {
	// // /**
	// // * 要执行的操作
	// // */
	// // RestartAPPTool.restartAPP(context);
	// // }
	// // }, 2000);// 3秒后执行Runnable中的run方法
	// }
	//
	// @Override
	// protected void onProgressUpdate(Integer... values) {
	// super.onProgressUpdate(values);
	// downProgress.setProgress(values[0]);
	// }
	//
	// @Override
	// protected Void doInBackground(Void... params) {
	// // ));
	// return null;
	// }
	//
	// /**
	// * 单例 keep an singleton instance of litehttp
	// */
	// private void initLiteHttp() {
	// if (liteHttp == null) {
	// HttpConfig config = new HttpConfig(context) // configuration
	// // quickly
	// .setDebugged(true) // log output when debugged
	// .setDetectNetwork(true) // detect network before connect
	// .setDoStatistics(true) // statistics of time and traffic
	// .setUserAgent("Mozilla/5.0 (...)") // set custom
	// // User-Agent
	// .setTimeOut(10000, 10000); // connect and socket
	// // timeout: 10s
	// liteHttp = LiteHttp.newApacheHttpClient(config);
	// } else {
	// liteHttp.getConfig() // configuration directly
	// .setDebugged(true) // log output when debugged
	// .setDetectNetwork(true) // detect network before connect
	// .setDoStatistics(true) // statistics of time and traffic
	// .setUserAgent("Mozilla/5.0 (...)") // set custom
	// // User-Agent
	// .setTimeOut(10000, 10000); // connect and socket
	// // timeout: 10s
	// }
	// }
	//
	// }

	private ProgressDialog m_pDialog;

	/**
	 * 请稍后...
	 */
	private void showWaitDialog() {
		m_pDialog = new ProgressDialog(context);
		m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		m_pDialog.setMessage("正在同步,请稍候...");
		m_pDialog.setIndeterminate(false);
		m_pDialog.setCancelable(false);
		m_pDialog.show();
	}

	/**
	 * 下载结束
	 */
	private void stopWaitDialog() {
		m_pDialog.hide();
	}

	/**
	 * 下载失败提示
	 */
	private void showDownloadFailure() {
		new AlertDialog.Builder(context).setTitle("数据同步失败").setMessage("是否重新同步?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						downloadFile(downFileUrl, downFilePath);
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}
}